<template>
  <div>
    <van-nav-bar title="注册账号" left-arrow @click-left="goBack" />
    <van-form @submit="register">
      <van-cell-group inset>
        <van-field v-model="phone" name="手机号码" label="手机号码" placeholder="手机号码" maxlength="11" type="digit" :rules="[{ required: true, message: '请填写手机号码' }]" />
        <van-field v-model="verifyCode" label="验证码" placeholder="验证码">
          <template #button>
            <van-button v-if="!time" size="mini" type="primary" @click="sendVerifyCode">获取验证码</van-button>
            <div v-else>{{ time }}秒后重试</div>
          </template>
        </van-field>
        <van-field v-model="name" name="姓名" label="姓名" placeholder="姓名" maxlength="4" :rules="[{ required: true, message: '请填写姓名' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码" :rules="[{ required: true, message: '请填写密码' }]" />
        <van-field v-model="rePassword" type="password" name="确认密码" label="确认密码" placeholder="确认密码" :rules="[{ required: true, message: '请再次确认密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          立即注册
        </van-button>
      </div>
    </van-form>
    <div class="info">千锋教育@2023-2025</div>
  </div>
</template>

<script>
import { showDialog } from 'vant';
export default {
  data() {
    return {
      time: 0,
      phone: '',
      verifyCode: '',
      name: '',
      password: '',
      rePassword: '',
    }
  },
  created() {
    this.phone = app.data.phone;
  },
  methods: {
    goBack() {
      this.$router.back();
    },
    async sendVerifyCode() {
      this.time = 120;
      this.timer = setInterval(()=>{
        this.time = this.time -1;
        if (!this.time) {
          clearInterval(this.timer);
        }
      }, 1000);
    },
    async register() {
      if (this.password !== this.rePassword) {
        return showDialog({ message: '两次输入的密码不一致' });
      }
      const data = await post('/create/member', {
        $uniq: 'phone',
        phone: this.phone,
        name: this.name,
        password: this.password,
      });
      if (!data.success) {
        return showDialog({ message: data.message });
      }
      showDialog({ message: '注册成功' });
      app.replace('/login', { phone: this.phone });
    }
  }
}
</script>


<style scoped lang="less">
.info {
  width: 100%;
  color: gray;
  margin-bottom: 40px;
  text-align: center;
  position: absolute;
  bottom: 20px;
}
</style>
